package com.pirestupppai.widgets.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.pirestupppai.R;
import com.pirestupppai.bean.FeedItem;
import com.pirestupppai.bean.TagItem;
import com.pirestupppai.common.Constant;
import com.pirestupppai.network.NetworkRequest;
import com.pirestupppai.network.TupaiSubscriber;
import com.pirestupppai.ui.activity.CommentActivity;
import com.pirestupppai.ui.activity.DetailActivity;
import com.pirestupppai.ui.activity.TagDetailActivity;
import com.pirestupppai.ui.activity.VideoTuttiActivity;
import com.pirestupppai.utils.ImageLoadUtil;
import com.pirestupppai.utils.Utils;
import com.pirestupppai.widgets.dialog.FeedMoreDialog;
import com.pirestupppai.widgets.dialog.ImageViewerDialog;
import com.pirestupppai.widgets.dialog.PsDialog;
import com.pirestupppai.widgets.dialog.VideoDialog;

import java.util.List;

import static android.widget.ListPopupWindow.WRAP_CONTENT;
import static android.widget.RelativeLayout.ALIGN_PARENT_LEFT;
import static android.widget.RelativeLayout.ALIGN_PARENT_RIGHT;
import static android.widget.RelativeLayout.CENTER_IN_PARENT;
import static android.widget.RelativeLayout.TRUE;
import static com.pirestupppai.utils.ImageLoadUtil.LoadOption.LOAD_BIG;

/**
 * 关注动态视图
 *
 * @author: xiaoluo
 * @date: 2017-04-12 17:50
 */
public class FeedView extends LinearLayout{
    private Context mContext;
    private FeedItem mFeedItem;

    private AvatarView mAvatar;
    private TextView mNicknameTv;
    private TextView mTimeTv;
    private RelativeLayout mPhotoLayout;
    private TextView mDescTv;
    private ImageView mLikeIv;
    private ImageView mCommentIv;
    private ImageView mPsIv;
    private ImageView mMoreIv;
    private ImageView mTogetherIv;
    private TextView mLikeCountTv;
    private TextView mCommentCountTv;
    private TextView mWorkCountTv;
    private FlowTagLayout mFeedTopicLayout;
    private AddLikeLayout mParentLayout;
    private FollowButton mFollowBtn;

    private String mImageUrl;

    private ScaleAnimation mLikeAnimation = new ScaleAnimation(0f, 1.0f, 0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

    public FeedView(Context context) {
        this(context,null);
    }

    public FeedView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);

    }

    public FeedView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        init();
    }

    private void init() {
        LayoutInflater.from(mContext).inflate(R.layout.widget_feed_view, this, true);
        mAvatar = (AvatarView) this.findViewById(R.id.feed_avatar);
        mNicknameTv = (TextView) this.findViewById(R.id.feed_nickname);
        mTimeTv = (TextView) this.findViewById(R.id.feed_time);
        mPhotoLayout = (RelativeLayout) this.findViewById(R.id.feed_photo_layout);
        mDescTv = (TextView) this.findViewById(R.id.feed_desc_tv);
        mLikeCountTv = (TextView) this.findViewById(R.id.feed_like_count);
        mLikeIv = (ImageView) this.findViewById(R.id.feed_like_iv);
        mMoreIv = (ImageView) this.findViewById(R.id.feed_more_iv);
        mTogetherIv = (ImageView) this.findViewById(R.id.feed_together_iv);
        mCommentCountTv = (TextView) this.findViewById(R.id.feed_comment_count);
        mWorkCountTv = (TextView) this.findViewById(R.id.feed_work_count);
        mCommentIv = (ImageView) this.findViewById(R.id.feed_comment_iv);
        mPsIv = (ImageView) this.findViewById(R.id.feed_ps_iv);
        mFeedTopicLayout = (FlowTagLayout) this.findViewById(R.id.feed_topic_layout);
        mFollowBtn = (FollowButton) this.findViewById(R.id.feed_follow_btn);

        if (mContext instanceof Activity) {
            mParentLayout = (AddLikeLayout) ((Activity) mContext).findViewById(R.id.add_like_layout);
        }

        initListeners();
    }

    public void initViews() {


    }

    private void initListeners() {
        mLikeIv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mFeedItem.isLiked()) {
                    mFeedItem.setLiked(true);
                    mLikeIv.setImageResource(R.drawable.ic_like_sel);
                    mLikeIv.startAnimation(mLikeAnimation);
                    mParentLayout.addLikeView();

                    NetworkRequest.getInstance().likeFeed(mFeedItem.getId(),
                            new TupaiSubscriber(mContext) {

                                @Override
                                protected void requestSuccess(Object o) {
                                    mFeedItem.setLike_count(mFeedItem.getLike_count() + 1);
                                    mLikeCountTv.setText(mFeedItem.getLike_count() + "");
                                }

                                @Override
                                protected void requestError(String error) {

                                }
                            });
                }
            }
        });

        mCommentIv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, CommentActivity.class);
                intent.putExtra(Constant.IntentKey.TARGET_ID, mFeedItem.getId());
                intent.putExtra(Constant.IntentKey.AVATAR, mFeedItem.getUser().getBg_image());
                intent.putExtra(Constant.IntentKey.NICKNAME, mFeedItem.getUser().getNickname());
                intent.putExtra(Constant.IntentKey.CONTENT, mFeedItem.getDesc());
                intent.putExtra(Constant.IntentKey.TIME, mFeedItem.getTpTime());
                intent.putExtra(Constant.IntentKey.UID, mFeedItem.getUser().getId());
                mContext.startActivity(intent);
            }
        });

        mDescTv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, CommentActivity.class);
                intent.putExtra(Constant.IntentKey.TARGET_ID, mFeedItem.getId());
                intent.putExtra(Constant.IntentKey.PHOTO_TYPE, mFeedItem.getType());
                intent.putExtra(Constant.IntentKey.AVATAR, mFeedItem.getUser().getBg_image());
                intent.putExtra(Constant.IntentKey.NICKNAME, mFeedItem.getUser().getNickname());
                intent.putExtra(Constant.IntentKey.CONTENT, mFeedItem.getDesc());
//                intent.putExtra(Constant.IntentKey.TIME, mPhotoItem.getCreate_time());
                intent.putExtra(Constant.IntentKey.UID, mFeedItem.getUid());
                mContext.startActivity(intent);
            }
        });

        mMoreIv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                FeedMoreDialog dialog = new FeedMoreDialog(mContext, mFeedItem);
                dialog.show();
            }
        });

        mPsIv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                PsDialog dialog = new PsDialog(mContext, mFeedItem);
                dialog.show();
            }
        });

        mTogetherIv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, VideoTuttiActivity.class);
                mContext.startActivity(intent);
            }
        });
    }

    /**
     * 设置视图
     */
    public void setViews(FeedItem item, ShowType type) {
        ShowType mShowType = type;
        int mLayoutWidth;
        if (mShowType == ShowType.SHOW_TYPE_DETAIL) {
            mLayoutWidth = Constant.WIDTH_OF_SCREEN - Utils.dpToPx(mContext, 60);
        } else {
            mLayoutWidth = Constant.WIDTH_OF_SCREEN;
        }
        mLikeAnimation.setDuration(500);

        mFeedItem = item;
        mNicknameTv.setText(mFeedItem.getUser().getNickname());
        mTimeTv.setText(mFeedItem.getTpTime());
        ImageLoadUtil.getInstance().loadAvatar(mFeedItem.getUser().getAvatar(), mAvatar);
        mAvatar.setUid(mFeedItem.getUser().getId(), false);
        mDescTv.setText(mFeedItem.getDesc());
        mLikeCountTv.setText(mFeedItem.getLike_count() + "");
        mCommentCountTv.setText(mFeedItem.getComment_count() + "");

        if (mFeedItem.isLiked()) {
            mLikeIv.setImageResource(R.drawable.ic_like_sel);
        } else {
            mLikeIv.setImageResource(R.drawable.ic_like);
        }

        if (mShowType == ShowType.SHOW_TYPE_LIST) {
            mFollowBtn.setVisibility(GONE);
        } else {
            mFollowBtn.setVisibility(VISIBLE);
            mFollowBtn.setFeedItem(mFeedItem);
        }

        // 话题数据,详情页不显示
        mFeedTopicLayout.removeAllViews();
        if (mShowType == ShowType.SHOW_TYPE_LIST) {
            mFeedTopicLayout.setVisibility(VISIBLE);
            LinearLayout.LayoutParams tagLp = new LinearLayout.LayoutParams(
                    WRAP_CONTENT, WRAP_CONTENT);
            tagLp.setMargins(Utils.dpToPx(mContext, 0), Utils.dpToPx(mContext, 0),
                    Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 10));
            final List<TagItem> tagList = mFeedItem.getTags();
            if (tagList != null && tagList.size() != 0) {
                for (int i = 0; i < tagList.size(); i++) {
                    final TextView tag = new TextView(mContext);
                    tag.setText(tagList.get(i).getText());
                    tag.setTextSize(13);
                    tag.setPadding(Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 9), Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 9));
                    tag.setTextColor(getResources().getColor(R.color.gray_text));
                    tag.setBackgroundResource(R.drawable.selector_search_flow_tag);
                    tag.setClickable(true);
                    tag.setTag(i);

                    tag.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent();
                            intent.setClass(mContext, TagDetailActivity.class);
                            intent.putExtra(Constant.IntentKey.ID, tagList.get((int) tag.getTag()).getId());
                            intent.putExtra(Constant.IntentKey.STAGGERED_TYPE, Constant.TYPE_REPLY);
                            intent.putExtra(Constant.IntentKey.TITLE, tagList.get((int) tag.getTag()).getText());
                            mContext.startActivity(intent);
                        }
                    });
                    mFeedTopicLayout.addView(tag, tagLp);
                }
            }
        } else {
            mFeedTopicLayout.setVisibility(GONE);
        }

        // 图片区域
        if (mFeedItem.getMedias() == null || mFeedItem.getMedias().size() == 0) {
            return;
        }
        mPhotoLayout.removeAllViews();
        LinearLayout.LayoutParams photolp = (LayoutParams) mPhotoLayout.getLayoutParams();
        photolp.height = mLayoutWidth;
        photolp.width = mLayoutWidth;
        mPhotoLayout.setLayoutParams(photolp);

        if (mFeedItem.getType() == FeedItem.ASK_PS_POST) {
            mWorkCountTv.setVisibility(VISIBLE);
            mWorkCountTv.setText(" · " + mFeedItem.getReply_count() + "个作品");
            mPsIv.setVisibility(VISIBLE);
            // 一张原图
            if (mFeedItem.getMedias().size() == 1) {
                mImageUrl = mFeedItem.getMedias().get(0).getPathname();
                ImageView askImage = new ImageView(mContext);
                askImage.setBackground(getResources().getDrawable(R.drawable.ic_zhanwei));
                askImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
                askImage.setLayoutParams(photolp);
                ImageLoadUtil.getInstance().loadImage(mImageUrl, askImage, LOAD_BIG);
                mPhotoLayout.addView(askImage);
                if (mShowType == ShowType.SHOW_TYPE_LIST) {
                    askImage.setOnClickListener(jumpListener);
                } else {
                    askImage.setOnClickListener(photoListener);
                }
            } else if (mFeedItem.getMedias().size() == 2) {
                // 两张原图
                ImageView leftImage = new ImageView(mContext);
                ImageView rightImage = new ImageView(mContext);

                RelativeLayout.LayoutParams leftParams = new RelativeLayout.LayoutParams(
                        mLayoutWidth / 2, mLayoutWidth);
                leftParams.addRule(ALIGN_PARENT_LEFT, TRUE);
                leftImage.setLayoutParams(leftParams);
                leftImage.setScaleType(ImageView.ScaleType.CENTER_CROP);

                RelativeLayout.LayoutParams rightParams = new RelativeLayout.LayoutParams(
                        mLayoutWidth / 2, mLayoutWidth);
                rightParams.addRule(ALIGN_PARENT_RIGHT, TRUE);
                rightImage.setLayoutParams(rightParams);
                rightImage.setScaleType(ImageView.ScaleType.CENTER_CROP);

                ImageLoadUtil.getInstance().loadImage(mFeedItem.getMedias().get(0).getPathname(), leftImage, LOAD_BIG);
                ImageLoadUtil.getInstance().loadImage(mFeedItem.getMedias().get(1).getPathname(), rightImage, LOAD_BIG);

                mPhotoLayout.addView(leftImage);
                mPhotoLayout.addView(rightImage);

                if (mShowType == ShowType.SHOW_TYPE_LIST) {
                    leftImage.setOnClickListener(jumpListener);
                    rightImage.setOnClickListener(jumpListener);
                } else {
                    leftImage.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showDialog(mFeedItem.getMedias().get(0).getPathname());
                        }
                    });
                    rightImage.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showDialog(mFeedItem.getMedias().get(1).getPathname());
                        }
                    });
                }

            }

            // 原图右上角小图标
            ImageView view = new ImageView(mContext);
            view.setImageResource(R.drawable.tag_single_ori);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);
            params.addRule(ALIGN_PARENT_RIGHT, TRUE);
            params.setMargins(Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 10), 0);
            view.setLayoutParams(params);
            mPhotoLayout.addView(view);

        } else if(mFeedItem.getType() == FeedItem.REPLY_PS_POST){
            // 作品类型
            mWorkCountTv.setVisibility(GONE);
            mImageUrl = mFeedItem.getMedias().get(0).getPathname();
            mPsIv.setVisibility(GONE);
            ImageView workImage = new ImageView(mContext);
            workImage.setBackground(getResources().getDrawable(R.drawable.ic_zhanwei));
            workImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
            workImage.setLayoutParams(photolp);
            mPhotoLayout.addView(workImage);
            ImageLoadUtil.getInstance().loadImage(mImageUrl, workImage, LOAD_BIG);


            if (mShowType == ShowType.SHOW_TYPE_LIST) {
                workImage.setOnClickListener(jumpListener);
            } else {
                workImage.setOnClickListener(photoListener);
            }

            // 作品原图区域
            if (mShowType == ShowType.SHOW_TYPE_LIST) {
                OriginImageLayout originImageLayout = new OriginImageLayout(mContext);
                originImageLayout.setImages(mFeedItem.getParent().getMedias());
                originImageLayout.setBackground(workImage);
                originImageLayout.init();
                mPhotoLayout.addView(originImageLayout);
            }
        } else {
            mTogetherIv.setVisibility(GONE);
            mPhotoLayout.removeAllViews();
            LinearLayout.LayoutParams videoLp = (LayoutParams) mPhotoLayout.getLayoutParams();
            videoLp.height = mLayoutWidth;
            videoLp.width = mLayoutWidth;
            mPhotoLayout.setLayoutParams(videoLp);

            if (mShowType == ShowType.SHOW_TYPE_LIST) {
                mTogetherIv.setVisibility(VISIBLE);
            }

            ImageView videoImage = new ImageView(mContext);
            videoImage.setLayoutParams(videoLp);
            ImageLoadUtil.getInstance().loadImage("", videoImage, LOAD_BIG);
            mPhotoLayout.addView(videoImage);

            ImageView playView = new ImageView(mContext);
            playView.setImageResource(R.drawable.record_play);
            RelativeLayout.LayoutParams playlp = new RelativeLayout.LayoutParams(Utils.dpToPx(mContext, 50),
                    Utils.dpToPx(mContext, 50));
            playlp.addRule(CENTER_IN_PARENT, TRUE);
            playlp.setMargins(Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 10), 0);
            playView.setLayoutParams(playlp);
            mPhotoLayout.addView(playView);

            mPhotoLayout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    VideoDialog dialog = new VideoDialog(mContext, "");
                    dialog.show();
                }
            });


            ImageView view = new ImageView(mContext);
            view.setImageResource(R.drawable.ic_video);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(Utils.dpToPx(mContext, 30),
                    Utils.dpToPx(mContext, 20));
            params.addRule(ALIGN_PARENT_RIGHT, TRUE);
            params.setMargins(Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 10), 0);
            view.setLayoutParams(params);
            mPhotoLayout.addView(view);
        }
    }

//    @Override
//    protected void onWindowVisibilityChanged(int visibility) {
//        super.onWindowVisibilityChanged(visibility);
//        if (visibility == View.VISIBLE){
////            WLog.d("danxx" ,"可见");
//            //开始某些任务
//        } else if(visibility == INVISIBLE || visibility == GONE){
//            if (videoView != null && videoView.isPlaying()) {
//                videoView.stopPlayback();
//            }
//        }
//    }

    private void showDialog(String url) {
        ImageViewerDialog dialog = new ImageViewerDialog(mContext, url);
        dialog.show();
    }

    private OnClickListener jumpListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setClass(mContext, DetailActivity.class);
            intent.putExtra(Constant.IntentKey.ID, mFeedItem.getId());
            mContext.startActivity(intent);
        }
    };

    private OnClickListener photoListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            showDialog(mImageUrl);
        }
    };

    public enum ShowType {
        SHOW_TYPE_LIST,    // 列表显示
        SHOW_TYPE_DETAIL,  // 详情显示
    }
}
